package com.zjq.security.security.handler;

import com.zjq.security.mapper.RoleMapper;
import com.zjq.security.pojo.Menu;
import com.zjq.security.pojo.Role;
import com.zjq.security.security.BaseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @User zhangjiaqi
 * @Project security
 * @Package com.zjq.security.security.handler
 * @Date 2022/3/28 22:02
 */
@Component
public class MySuccesHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RoleMapper roleMapper;

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // super.onAuthenticationSuccess(request, response, authentication);
        // response.sendRedirect("/success.html");
        response.getWriter().write("denglu success");

        BaseUser baseUser = (BaseUser) authentication.getPrincipal();//获取登录方法返回的对象

        //String username = principal.getUsername();
        //根据username再查询一下id,但是我觉得太麻烦

        //获取到用户的权限
        List<Role> roleList = roleMapper.findRoleByUserIdWithMenu(baseUser.getUserId());
        Set<String> allPermisson = new HashSet<>();//用户所有的权限
        roleList.forEach(role -> {
            List<Menu> menusList = role.getMenuList();
            List<String> permissonList = menusList.stream().map(Menu::getPermission).collect(Collectors.toList());
            allPermisson.addAll(permissonList);
        });


        //更新用户的权限,将用户的权限字符串转成security中的权限对象
        List<SimpleGrantedAuthority> authorityList = allPermisson.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        //刷新用户的权限
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(baseUser,authentication.getCredentials(),authorityList));

    }
}
